import Taro, { useReachBottom } from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { View, Image, Text } from '@tarojs/components';
import { AtMessage } from 'taro-ui';
import "taro-ui/dist/style/components/button.scss"; // 按需引入
import Header from '@/components/header';
import Return from '@/components/Return';
import SurveyCard from '@/components/SurveyCard';
import { getSurverList } from '@/api/application/pollsandSurvey';
import { noactivity } from '../image.js';
import css from './index.module.less';

/**
 * 应用/投票调查
 */
export default function PollsAndSurvey() {
  const [classesFlag, setClassesFlag] = useState(false); // 是否有投票记录标志的标志
  const [surveyList, setSurveyList] = useState([]);
  //用户信息
  const [userInfo, setUserInfo] = useState({});
  //当前页数
  const [current, setCurrent] = useState(1);
  //当前页内容数
  const pageSize = 9;

  useEffect(() => {
    Taro.getStorage({
      key: 'userInfo',
      success: function (a) {
        setUserInfo(a.data);
        if (a.data.isAudited !== 1) {
          Taro.atMessage({
            'message': '您还未进行认证',
            'type': 'error',
            'duration': 2000
          });
        } else {
          getSurverList(a.data.organizationId, current, pageSize).then((res) => {
            if (res.data.length !== 0) {
              setClassesFlag(true);
              setSurveyList(res.data);
            }
          });
        }
      }
    });
  }, []);

  useReachBottom(() => {
    getSurverList(userInfo.organizationId, current + 1, pageSize).then(res => {
      if (res.code === 200) {
        setSurveyList([...surveyList, ...res.data]);
      }
    });
    setCurrent(current + 1);
  });

  const clickCard = (e, voteId) => {
    const jsonData = {
      voteId,
      partyId: userInfo.partyId,
    };
    const data = JSON.stringify(jsonData);
    Taro.navigateTo({ url: `./surveydtl/index?data=${data}` });
  };

  return (
    <View className={css.home}>
      <Header message='投票调查' left='140px' />
      <Return />
      <View className={css.content}>
        <AtMessage />
        {
          userInfo.isAudited !== 1 ? <View className={css.noAudited}><View>您还未进行认证</View></View> :
            <View className={css.audited}>
              {(classesFlag && surveyList.length !== 0) ?
                surveyList.map((item) => {
                  return (
                    <View
                      key={item.voteId}
                      onClick={e => item.voteStatus > 0 ? clickCard(e, item.voteId) : () => { }}
                    >
                      <SurveyCard info={item} />
                    </View>
                  );
                })
                :
                <View className={css.noActivity}>
                  <Image className={css.noActivityImage} src={noactivity} />
                  <Text className={css.font}>暂无任何投票</Text>
                </View>
              }
            </View>
        }
      </View>
    </View >
  );
}